package com.thon.service.topic;

import com.thon.commons.persistence.Page;
import com.thon.commons.utils.StringUtils;
import com.thon.dao.topic.TopicDao;
import com.thon.entity.topic.Topic;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by Chen on 2016/2/9.
 */
@Service
@Transactional
public class TopicService {

    @Autowired
    private TopicDao topicDao;

    public Topic getTopic(int id){
        return topicDao.get(id);
    }

    public void saveTopic(Topic topic){
        topicDao.save(topic);
    }

    public void delTopic(Topic topic){
        topicDao.delete(topic);
    }

    public Page<Topic> findTopics(Page<Topic> page, Topic topic) {
        DetachedCriteria dc = topicDao.createDetachedCriteria();

        if (topic.getCreatorType() != null) {
            dc.add(Restrictions.eq("creatorType", topic.getCreatorType()));
        }
        if (topic.getCreator() != null) {
            dc.add(Restrictions.eq("creator.id", topic.getCreator().getId()));
        }
//        if (topic.getCreator() != null && topic.getCreatorType() == 1) {
//            dc.add(Restrictions.ne("creator.id", topic.getCreator().getId()));
//        }
        if (topic.getDirectTeacher() != null) {
            dc.add(Restrictions.eq("directTeacher.id", topic.getDirectTeacher().getId()));
        }

        dc.addOrder(Order.desc("id"));

        return topicDao.find(page, dc);
    }

    public boolean hasPushTopic(Integer id) {
        List<Topic> topicList = topicDao.hasPushTopic(id);
        if (topicList.size() == 0) {
            return false;
        } else {
            return true;
        }
    }
}
